﻿@page "/news/add"
@page "/news/edit/{newsId:int}"
@using Whu.BLM.NewsSystem.Client.Services
@using Whu.BLM.NewsSystem.Shared.Entity.Content
@using System.ComponentModel.DataAnnotations
@using Whu.BLM.NewsSystem.Client.Exceptions
@using Whu.BLM.NewsSystem.Shared.Entity.Identity
@inject MessageService _message
@inject INewsCategoryService _newsCategoryService
@inject INewsService _newsService
@inject NavigationManager _navigationManager

<Form Model="@News"
      LabelColSpan="4"
      WrapperColSpan="20"
      OnFinish="OnConfirmEditing">
    <FormItem Label="标题">
        <Input @bind-Value="@context.Title"/>
    </FormItem>
    <FormItem Label="URL">
        <Input @bind-Value="@context.OriginUrl"/>
    </FormItem>
    <FormItem Label="类别">
        <Select Mode="default"
                DataSource="@NewsCategories"
                LabelName="@nameof(NewsCategory.Name)"
                ValueName="@nameof(NewsCategory.Id)"
                @bind-Value="@context.NewsCategory">
        </Select>
    </FormItem>
    <FormItem Label="摘要">
        <TextArea @bind-Value="@context.AbstractContent" MinRows="5" MaxRows="10"></TextArea>
    </FormItem>
    <div style="width: 100%; display: flex; justify-content: flex-end">
        <Button Type="@ButtonType.Default" HtmlType="submit">提交修改</Button>
    </div>
</Form>

@code {

    [CascadingParameter]
    private Task<AuthenticationState> AuthenticationState { get; set; }

    [Parameter]
    public int? NewsId { get; set; }

    class NewsModel
    {
        [Required(ErrorMessage = "请输入标题")]
        [MinLength(5, ErrorMessage = "摘要内容不得小于5字符")]
        public string Title { get; set; }

        [Required(ErrorMessage = "请输入新闻摘要")]
        [MinLength(20, ErrorMessage = "摘要内容不得小于20字符")]
        public string AbstractContent { get; set; }

        [Required(ErrorMessage = "请输入新闻URL")]
        [Url(ErrorMessage = "请输入一个合法的URL")]
        public string OriginUrl { get; set; }

        [Required(ErrorMessage = "请输入新闻类别")]
        public int NewsCategory { get; set; }
    }

    private NewsModel News { get; set; } = new NewsModel();
    private IList<NewsCategory> NewsCategories { get; set; } = new List<NewsCategory>();

    protected override async Task OnInitializedAsync()
    {
        if (!(await AuthenticationState).User.IsInRole(UserGroup.Admin.ToString()))
        {
    // 没有权限访问编辑和添加，所以导航至首页
            await _message.Error("您无权访问本页面！");
            _navigationManager.NavigateTo("/");
        }
        NewsCategories = await _newsCategoryService.GetNewsCategoriesAsync();
    }

    protected override async Task OnParametersSetAsync()
    {
        if (NewsId == null)
        {
    // 认为是新增新闻
            News = new NewsModel()
            {
                Title = string.Empty,
                OriginUrl = string.Empty,
                AbstractContent = string.Empty,
                NewsCategory = 0
            };
        }
        else
        {
    // 编辑指定的新闻
            try
            {
                var news = await _newsService.GetNewsById((int) NewsId);
                News = new NewsModel()
                {
                    Title = news.Title,
                    OriginUrl = news.OringinUrl,
                    AbstractContent = news.AbstractContent,
                    NewsCategory = news.NewsCategory.Id
                };
            }
            catch (NewsNotFoundException e)
            {
                await _message.Error(e.Message);
                _navigationManager.NavigateTo("/");
            }
        }
    }

    private async Task OnConfirmEditing()
    {
        if (NewsId == null)
        {
            try
            {
                await _newsService.AddNews(News.NewsCategory, new News()
                {
                    Title = News.Title,
                    AbstractContent = News.AbstractContent,
                    OringinUrl = News.OriginUrl
                });
                await _message.Info("您的添加已通过");
            }
            catch (AddNewsException e)
            {
                await _message.Error($"添加新闻失败：{e.Message}");
            }
        }
        else
        {
            try
            {
                await _newsService.UpdateNews(News.NewsCategory, new News()
                {
                    Id = (int) NewsId,
                    Title = News.Title,
                    AbstractContent = News.AbstractContent,
                });
                await _message.Info("您的编辑已通过");
            }
            catch (AddNewsException e)
            {
                await _message.Error($"编辑新闻失败：{e.Message}");
            }
        }
    }

}